/**
 * 
 */
package com.example.com.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;

/**
 * 获取屏幕高宽、像素密度
 * 
 * @author alonso lee
 * 
 */
public class ALDisplayMetricsManager {
	public static final int SCREEN_HEIGHT_NORMAL = 480;
	private static int STATUS_BAR_HEIGHT = -1;

	/**
	 * 获取屏幕高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context) {
		/* 获取手机屏幕分辨率 */
		DisplayMetrics dm = new DisplayMetrics();
		WindowManager winManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		winManager.getDefaultDisplay().getMetrics(dm);
		return dm.heightPixels;
	}

	/**
	 * 获取屏幕宽度
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		WindowManager winManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		winManager.getDefaultDisplay().getMetrics(dm);
		return dm.widthPixels;
	}


	/**
	 * 得到我们的状态栏的高度
	 * @param activity Activity
	 * @return 状态栏的高度
	 */
	public static int getStatusBarHeight(Activity activity) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && STATUS_BAR_HEIGHT == -1) {
			try {
				final Resources res = activity.getResources();
				// 尝试获取status_bar_height这个属性的Id对应的资源int值
				int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
				if (resourceId <= 0) {
					Class<?> clazz = Class.forName("com.android.internal.R$dimen");
					Object object = clazz.newInstance();
					resourceId = Integer.parseInt(clazz.getField("status_bar_height")
							.get(object).toString());
				}

				// 如果拿到了就直接调用获取值
				if (resourceId > 0)
					STATUS_BAR_HEIGHT = res.getDimensionPixelSize(resourceId);

				// 如果还是未拿到
				if (STATUS_BAR_HEIGHT <= 0) {
					// 通过Window拿取
					Rect rectangle = new Rect();
					Window window = activity.getWindow();
					window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
					STATUS_BAR_HEIGHT = rectangle.top;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return STATUS_BAR_HEIGHT;
	}

}
